import traceback
from django.http import HttpResponse

from .forms import SaveFileForm
from .check_invoice import check_invoice_img
import datetime
import os
from pathlib import Path
import json

from pywebsite.util import download_image
from pywebsite.util import pdf_to_jpg
import requests
import uuid
# Create your views here.

BASE_DIR = Path(__file__).resolve().parent.parent
PROJECT_ROOT = os.path.join(BASE_DIR,'InvoiceOCR')
InvoiceOCR_MEDIA_ROOT = os.path.join(PROJECT_ROOT,'imgs')


def recognize_invoice(request):
    if request.method == 'POST':
        form = SaveFileForm(request.POST, request.FILES)

        if form.is_valid():
            files = request.FILES.getlist('file')
            file_url = form.cleaned_data['fileUrl']
            if len(file_url)+len(files) <= 0:
                return HttpResponse("图片问题,没有图片")

            fid = "%s" % uuid.uuid4()

            resource_file_name = fid

            if len(files) > 0:
                resource_file_name = files[0].name
            if len(file_url.split("/")) > 1:
                resource_file_name = file_url.split("/")[len(file_url.split("/")) - 1]

            filename = fid + '-source-' + resource_file_name
            filepath = os.path.join(InvoiceOCR_MEDIA_ROOT, filename)

            # 传的链接-下载图片
            if len(file_url) > 0:
                err, filepath = download_image(file_url, filepath)
                if err:
                    return HttpResponse("图片下载失败,"+err)

            filename_ret = os.path.basename(filepath).replace("-source-", "-ret-")
            filename_err = os.path.basename(filepath).replace("-source-", "-err-")
            fileretpath = os.path.join(InvoiceOCR_MEDIA_ROOT, filename_ret)
            fileerrpath = os.path.join(InvoiceOCR_MEDIA_ROOT, filename_err)

            # 直接传图
            if len(files) > 0:
                # save_file = SaveFileModel()
                # save_file.save()
                destination = open(filepath, 'wb+')
                if len(files) > 0:
                    for chunk in files[0].chunks():
                        destination.write(chunk)
                    destination.close()

            try:
                invoice = None
                if filepath.endswith('.pdf'):
                    # 只返回最多3页,且只返回识别到的第一张发票
                    file_list = pdf_to_jpg(filepath)
                    for filep in file_list:
                        if filep:
                            invoice, ret_img = check_invoice_img(filep, debug=request.GET.__contains__('debug'))
                            invoice.page_count = len(file_list)
                            if request.GET.__contains__('debug'):
                                ret_img.save(fileretpath.replace('.pdf', '.jpg').replace('.PDF', '.jpg'))
                        # os.remove(filep)
                        if invoice.valid():
                            break
                else:
                    invoice, ret_img = check_invoice_img(filepath, debug=request.GET.__contains__('debug'))
                    if request.GET.__contains__('debug'):
                        ret_img.save(fileretpath)

                if invoice:
                    invoice.check_uid = fid
                    invoice_str = json.dumps(invoice.to_dict(),ensure_ascii=False)

                    if os.path.isfile(filepath):
                        os.remove(filepath)
                    return HttpResponse(invoice_str + "," + "/InvoiceOCR/imgs/" + filename_ret)

                if os.path.isfile(filepath):
                    os.remove(filepath)
                return HttpResponse("no invoice found")
            except Exception as e:
                if len(file_url) > 0:
                    if os.path.isfile(filepath):
                        os.rename(filepath, fileerrpath)
                if len(files) > 0:
                    if os.path.isfile(filepath):
                        os.rename(filepath, fileerrpath)
                if os.path.isfile(filepath):
                    os.remove(filepath)
                print(e)
                traceback.print_exc()
                if len(e.args) > 0:
                    return HttpResponse("图片验证失败,无法保存下载文件或未识别到文字,报错:"+e.args[0])
                return HttpResponse("图片验证失败,报错,")
        return HttpResponse(form.errors)
    else:
        return HttpResponse("使用POST - form-data调用")
